<template>
  <div>
    <!-- 顶部搜索 -->
    <form action="/" class="search">
      <van-search v-model="searchText" placeholder="请输入搜索关键词" show-action
                  background="#3296fa"
                  @search="onSearch"
                  @cancel="onCancel"
                  @focus="isResultShow=false"
      />
    </form>
    <!-- 搜索结果列表 -->
    <searchResult v-if="isResultShow" :searchText="searchText"></searchResult>
    <!-- 联想搜索 -->
    <searchSuggestion v-else-if="searchText" :searchText="searchText" @search="onSearch"></searchSuggestion>
    <!-- 搜索历史 -->
    <searchHistory :searchHistoryList="searchHistoryList" @search="onSearch" @clearAll="searchHistoryList=[]"
                   v-else></searchHistory>
  </div>
</template>

<script>
import searchHistory from './components/search-history.vue'
import searchResult from './components/search-result.vue'
import searchSuggestion from './components/search-suggestion.vue'
import { setItem, getItem } from '../../utils/storage.js'

export default {
  name: 'searchIndex',
  components: {
    searchHistory,
    searchResult,
    searchSuggestion
  },
  data () {
    return {
      searchText: '',
      isResultShow: false, // 是否展示搜索结果
      searchHistoryList: getItem('TOUTIAO_SEARCHHISTORY') || []
    }
  },
  watch: {
    'searchHistoryList' () {
      setItem('TOUTIAO_SEARCHHISTORY', this.searchHistoryList)
    }
  },
  methods: {
    onSearch (val) {
      // 更新文本框内容
      this.searchText = val
      // 判断输入框内容是否为空，如果为空不允许进行查询
      if (this.searchText.trim().length === 0) return
      // 存储添加历史搜索记录
      // 在添加元素之前先把原数组中的相同元素给删除
      const index = this.searchHistoryList.indexOf(this.searchText)
      if (index !== -1) {
        // 找到了相同的元素，把找到的元素给删除掉
        this.searchHistoryList.splice(index, 1)
      }
      // unshift 向数组的开头添加一个或更多元素
      this.searchHistoryList.unshift(this.searchText)
      // 开启搜索结果 输入内容后敲击回车时触发的查询方法
      this.isResultShow = true
    },
    onCancel () {
      // 点击取消按钮时触发的方法 => 返回上一页
      this.$router.back()
    }
  }
}
</script>

<style scoped lang="less">
.search-container {

  padding-top: 54px;

  .search {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }

  .van-search__action {
    color: #fff;
  }
}
</style>
